import "babel-polyfill";
import csshook from 'css-modules-require-hook/preset'
//在node中处理css的插件
import assethook from 'asset-require-hook'
import path from 'path';
// 处理图片的插件
assethook({
  extensions: ['png', 'jpg', 'gif'],
})

import staticPath from './build/asset-manifest.json';
//静态文件名字
import Koa from 'koa';
const app = new Koa();

import views from 'koa-views'
import json from 'koa-json'
import onerror from 'koa-onerror'
import bodyparser from 'koa-bodyparser'
import logger from 'koa-logger'
import React from 'react';
const koaStaticPlus =require('koa-static-plus')
import { renderToString, renderToNodeStream } from 'react-dom/server';
//这个是react官方的服务端渲染方法


import {
  BrowserRouter,  //这个是给客户端渲染用的
  StaticRouter,   //这个是给服务端渲染用的
  Route,
  Switch,
  hashHistory,
  IndexRoute,
  Redirect,
  Link,
} from 'react-router-dom';
import Content from './src/router';

import { Provider } from 'react-redux'
import store from './src/store/index.js'




onerror(app)

app.use(bodyparser({
  enableTypes: ['json', 'form', 'text']
}))
app.use(json())
app.use(logger())

app.use(koaStaticPlus(path.join(__dirname, '/build/static'), {
  pathPrefix: '/static/'  //路径前缀
}))
app.use(views(__dirname + '/views', {
  extension: 'ejs'
}))


app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})


app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});



// 服务端渲染在这里呢
app.use(async (ctx, next) => {

  let context = {}
  var cont = renderToString(
    <Provider store={store}>
      <StaticRouter
        location={ctx.url}    //配置url 让react知道url
        context={context}
      >
        <Content />
      </StaticRouter>
    </Provider>
  )

  let pageHtml = `
  <!DOCTYPE html>
  <html lang="en">
  <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>服务端渲染</title>
      
      <link rel="stylesheet" href="${staticPath['main.css']}">
      <!-- 引入highlight  -->
      <link href="http://cdn.bootcss.com/highlight.js/8.0/styles/monokai_sublime.min.css" rel="stylesheet">
  </head>
  <body>
  asdasdasd
      <div id="root">
      ${cont}
      </div>
  </body>
  </html>
  <script type="text/javascript" src="${staticPath['main.js']}"></script>
  `
  ctx.body = pageHtml
})


module.exports = app
